package com.bamboo.framework.common.qiniu.kodo.util.impl;

import com.bamboo.framework.common.enums.Status;
import com.bamboo.framework.common.format.ReturnMsg;
import com.bamboo.framework.common.qiniu.kodo.config.BucketProperties;
import com.bamboo.framework.common.qiniu.kodo.config.KodoProperties;
import com.bamboo.framework.common.qiniu.kodo.util.UploadFiles;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.model.DefaultPutRet;
import java.io.InputStream;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;

/**
 * @Author: GuoQing
 * @Date: 2019/1/29 15:28
 * @description 千牛文件上传接口实现类
 */
@Component
public class UploadFilesImpl implements UploadFiles {

  @Resource
  private KodoProperties kodoProperties;

  @Override
  public ReturnMsg uploadFiles(InputStream file, BucketProperties bucketProperties, String key) throws QiniuException {
    BucketProperties bucketProperties1 = kodoProperties.getBucket(bucketProperties);
    Response response = bucketProperties1
        .getUploadManager().put(file, key, bucketProperties1.getUpToken(), null, null);
    DefaultPutRet defaultPutRet = getDefaultPutRet(response);
    String hashurl = bucketProperties1.getUrl(defaultPutRet.hash);
    String keyurl = bucketProperties1.getUrl(defaultPutRet.key);
    return new ReturnMsg((int) Status.SUCCESS.getCode(), hashurl, keyurl);
  }


  @Override
  public ReturnMsg uploadFiles(String localFilePath, BucketProperties bucketProperties, String key)
      throws QiniuException {
    BucketProperties bucketProperties1 = kodoProperties.getBucket(bucketProperties);
    Response response = bucketProperties1
        .getUploadManager().put(localFilePath, key, bucketProperties1.getUpToken());
    DefaultPutRet defaultPutRet = getDefaultPutRet(response);
    String hashurl = bucketProperties1.getUrl(defaultPutRet.hash);
    String keyurl = bucketProperties1.getUrl(defaultPutRet.key);
    return new ReturnMsg((int) Status.SUCCESS.getCode(), hashurl, keyurl);
  }

  @Override
  public ReturnMsg uplodImage(InputStream file) {
    return this.uplodImage(UUID.randomUUID().toString(), null, file);
  }

  @Override
  public ReturnMsg uplodImage(String fileName, InputStream file) {
    return this.uplodImage(fileName, null, file);
  }

  @Override
  public ReturnMsg uplodImage(String fileName, BucketProperties bucketProperties, InputStream file) {
    ReturnMsg msg = null;
    try {
      msg = this.uploadFiles(file, bucketProperties, fileName);
    } catch (QiniuException e) {
      e.printStackTrace();
      msg = new ReturnMsg(e.code(), e.error(), e.response.toString());
    }
    return msg;
  }

  public DefaultPutRet getDefaultPutRet(Response response) throws QiniuException {
    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    return putRet;
  }
}
